package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-24
 */
@Service
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<ProductSkuVo> getProductSkuVoList() {
        //查询所有sku 并按销量倒叙展示20条
        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuVoList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getId, skuId).select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSkuId(skuId);
        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getId, id).select(ProductSku::getSkuSpec);
        List<ProductSku> productSkus = baseMapper.selectList(queryWrapper);
        Map<String, Long> map = new HashMap<>();
        for (ProductSku skus : productSkus) {
            map.put(skus.getSkuSpec(), skus.getId());
        }
        return map;
    }

    /**
     * 根据skuId查询sku商品信息
     *
     * @param skuId skuId
     * @return ProductSku
     */
    @Override
    public ProductSku getProductSku(Long skuId) {
        // 获取锁
        String lockKey = "product:sku:lock:" + skuId;
        // 生成一个不重复的值，作为锁的标识，在并发情况下，在释放锁之前，比对一下锁是不是自己的，防止误删
        String lockValue = UUID.randomUUID().toString().replace("-", "");
        // 先从redis中获取商品，若存在，则直接返回，不存在则从数据库中获取
        // 此方法用于向redis中设置锁，若锁存在，则返回false，若锁不存在，则返回true
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.SECONDS);// 设置锁的过期时间，防止死锁 相当于SETNX
        if (flag) {
            try {
                // 获取锁成功，则从redis中获取商品信息
                String dataKey = "product:sku:" + skuId;// 商品信息缓存key
                ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                // 判断商品信息是否为空，若不为空，则直接返回，若为空，则从数据库中获取商品信息
                if (productSku != null) {
                    log.warn("从redis中获取商品信息成功");
                    return productSku;
                }
                log.warn("从redis中获取商品信息失败，从数据库中获取商品信息");
                productSku = baseMapper.selectById(skuId);
                // 若商品信息不为空，则将商品信息存入redis中，并设置过期时间，若为空，存储一个new对象，并设置过期时间
                // 因为如若不新建对象 则后续每次都会去查询数据库，会存在缓存穿透(一定程度上解决 并非完全能解决 被恶意攻击一样会大量访问数据库造成崩溃)
                long ttl = productSku == null ? 60 : 10 * 60; //十分钟
                if (productSku == null) {
                    productSku = new ProductSku();
                }
                redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.SECONDS);
                return productSku;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                // 释放锁
                String script = """
                    if redis.call('get', KEYS[1]) == ARGV[1] then
                        return redis.call('del', KEYS[1])
                    else
                        return 0
                    end
                    """;// lua脚本 相当于这段原始代码(非lua脚本)
                /*if (lockValue.equals(redisTemplate.opsForValue().get(lockKey))) {
                    // 删除键
                    Boolean result = redisTemplate.delete(lockKey);
                    return result ? 1L : 0L; // 返回 1 表示删除成功，0 表示删除失败
                } else {
                    return 0L; // 值不匹配或键不存在
                }*/
                Long lock = (Long) redisTemplate.execute(
                        new DefaultRedisScript<>(script, Long.class),
                        List.of(lockKey),
                        lockValue);
                System.out.println("释放锁的结果为：" + lock);
            }
        }else {
            try {
                // 获取锁失败，则休眠一段时间后重试
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return getProductSku(skuId);// 自旋
    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductSku::getId, skuIdList)
                    .select(ProductSku::getId, ProductSku::getSalePrice);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(productSkuList)){
            return productSkuList.stream().map(productSku -> {
                SkuPriceVo skuPriceVo = new SkuPriceVo();
                skuPriceVo.setSkuId(productSku.getId());
                skuPriceVo.setSalePrice(productSku.getSalePrice());
                return skuPriceVo;
            }).toList();
        }
        return null;
    }
}
